<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/" style="font-size: 12px">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            @input="search"
            v-model="queryInfo.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              @click="search"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDia = true">添加</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="users" style="width: 100%" border>
        <!--  -->
        <el-table-column type="index" label="#" width="40"> </el-table-column>
        <!--  -->
        <el-table-column prop="username" label="姓名" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="150">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="120">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <!-- 状态 -->
          <template slot-scope="scope">
            <el-switch
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeStatus(scope.row)"
              v-model="scope.row.mg_state"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="Edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="del(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="small"
              @click="assignRoles(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDia" width="50%">
      <el-form
        :model="addUserForm"
        ref="addUserRef"
        :rules="addUserRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addUserForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDiaNo">取 消</el-button>
        <el-button type="primary" @click="addDiaOk">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog title="分配角色" :visible.sync="EditDia" width="50%">
      <el-form
        :model="addUserForm"
        ref="editUserRef"
        :rules="addUserRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addUserForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="EditDiaNo">取 消</el-button>
        <el-button type="primary" @click="EditDiaOk">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 弹框 -->
    <el-dialog
      title="收货地址"
      :visible.sync="assignDia"
      style="text-align: left"
    >
      <el-form>
        <el-form-item>
          当前用户:
          {{ CurrentUser.username }}
        </el-form-item>
        <el-form-item
          >当前角色:
          {{ CurrentUser.role_name }}
        </el-form-item>
        <el-form-item label="分配新角色">
          <el-select
            placeholder="请选择"
            v-model="assignRolesForm.currentRolesId"
          >
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDiaOk = false">取 消</el-button>
        <el-button type="primary" @click="assignDiaOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { lodash } from "lodash";

export default {
  data() {
    // 验证邮箱
    const checkEmail = (rule, value, callback) => {
      // 正则验证
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!reg.test(value)) {
        callback(new Error("该邮箱不合法 请正确输入 "));
      }
      callback();
    };
    // 验证手机号
    const checkMobile = (rule, value, callback) => {
      const reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请正确输入手机号"));
      }
      callback();
    };
    return {
      users: [], //用户列表数据
      total: 0,
      addDia: false, //添加的弹框
      addUserForm: {}, // 添加的表单数据
      EditDia: false, //编辑弹框的数据
      assignDia: false, //分配角色的弹框
      assignRolesForm: {}, //分配角色表单数据
      CurrentUser: {},
      selectList: {}, //下拉菜单的数据
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],

        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 渲染
    async getUserList() {
      const res = await this.$API.getUserListApi(this.queryInfo);
      console.log("用户列表", res);
      this.userList = res;
      let { total, users } = res;
      this.users = users;
      this.total = total;
    },
    // 添加弹框取消
    addDiaNo() {
      this.addDia = false;
    },
    // 添加弹框确定
    addDiaOk() {
      this.$refs.addUserRef.validate(async (valid) => {
        //验证
        if (!valid) return false;
        await this.$API.addUserApi(this.addUserForm); //请求接口
        this.addDia = false; //弹框隐藏
        this.getUserList(); //重新调用
      });
    },
    // 删除
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$API.delUserApi(id);
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击编辑按钮 弹出 回填
    Edit(row) {
      this.addUserForm = row;
      this.EditDia = true;
    },
    // 编辑弹框取消
    EditDiaNo() {
      this.EditDia = false;
    },
    // 编辑弹框确定
    EditDiaOk() {
      this.$refs.editUserRef.validate(async (valid) => {
        if (!valid) return false;
        const { id, email, mobile } = this.addUserForm;
        await this.$API.editUserApi(id, { email, mobile });
        this.EditDia = false;
        this.getUserList();
      });
    },
    // 搜索
    search: _.debounce(function () {
      this.getUserList();
    }, 300),
    // 分配
    async assignRoles(user) {
      this.CurrentUser = user;
      console.log("user", user);

      const res = await this.$API.getUserRolesListApi();
      console.log("sessign", res);
      this.selectList = res;
      this.assignDia = true;
    },
    // 点击分配按钮 确定
    async assignDiaOk() {
      const { id } = this.CurrentUser;
      const { currentRolesId } = this.assignRolesForm;
      await this.$API.sessignRolesApi(id, currentRolesId);

      this.assignDia = false;
      this.getUserList();
    },
    // 修改状态

    async changeStatus(row) {
      const { id, mg_state: mgState } = row;
      await this.$API.statusUserApi(id, mgState);
      this.getUserList();
    },
    // 分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
  },
  components: {},
};
</script>

<style lang='scss'>
.el-card {
  margin-top: 15px;
}
.el-row {
  margin: 0 !important;
  padding: 0 !important;
}
.el-table {
  margin-top: 15px;
  text-align: center;
}
</style>
